import logging

from src.core.models.dto import UserDTO
from src.database.uow import SQLAlchemyUoW
from src.domain.user import UserEntity

logger = logging.getLogger(__name__)


class UserService:
    def __init__(self, uow: SQLAlchemyUoW):
        self._uow = uow

    async def get_user_by_id(self, user_id: int) -> UserDTO:
        """Получаем пользователя по id"""

        return await self._uow.user_reader.get_user_by_id(user_id)

    async def get_user_by_telegram_id(self, user_tg_id: int) -> UserDTO:
        """Получаем пользователя по telegram id"""

        return await self._uow.user_reader.get_user_by_tg_id(user_tg_id)

    async def get_user_by_phone_number(self, phone_number: str) -> UserDTO:
        """Получаем пользователя по номеру телефона"""

        return await self._uow.user_reader.get_user_by_phone_number(phone_number)

    async def update_user(
        self,
        user_id: int,
        name: str | None = None,
        telegram_id: int | None = None,
        phone: str | None = None,
        email: str | None = None,
        onboarding: bool | None = None,
    ) -> UserDTO:
        """Обновляем пользователя"""

        user: UserEntity = await self._uow.user_repo.acquire_user_by_id(user_id)
        if name:
            user.name = name
        if telegram_id:
            user.telegram_id = telegram_id
        if phone:
            user.phone = phone
        if email:
            user.email = email
        if onboarding:
            user.onboarding = onboarding

        user: UserDTO = await self._uow.user_repo.update_user(user)

        await self._uow.commit()

        return user

    async def create_user(self, phone: str) -> UserDTO:
        """Создаем пользователя"""

        user = UserEntity.create(phone=phone)
        try:
            user = await self._uow.user_repo.create_user(user)
        except Exception as err:
            await self._uow.rollback()
            raise err

        await self._uow.commit()
        return user
